package cn.cqnu.service.impl;

import cn.cqnu.domin.entity.Student;
import cn.cqnu.domin.vo.ResponseResult;
import cn.cqnu.domin.vo.StudentInfoVo;
import cn.cqnu.global.SystemConstant;
import cn.cqnu.global.SystemReturnEnum;
import cn.cqnu.mapper.StudentMapper;
import cn.cqnu.service.StudentService;
import cn.cqnu.utils.BeanCopyUtil;
import cn.cqnu.utils.JWTUtils;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * (Student)表服务实现类
 *
 * @author lkzy
 * @since 2024-01-19 20:15:18
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Override
    public ResponseResult register(Student temp) {

        // TODO 学号相同的情况
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStudentId, temp.getStudentId());
        Student r = getOne(wrapper);

        if (r != null) {
            return ResponseResult.error(SystemReturnEnum.ID_EXIST);
        }

        temp.setStudentPassword(SecureUtil.md5(temp.getStudentPassword()));
        save(temp);
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult login(Long studentId, String password) {
        // 密码加密
        password = SecureUtil.md5(password);
        // 比对
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStudentId, studentId).eq(Student::getStudentPassword, password);
        Student res = getOne(wrapper);
        if (res == null) {
            //    登录信息有误
            return ResponseResult.error(SystemReturnEnum.LOGIN_INFO_WRONG);
        }

        // 颁发jwt
        String token = JWTUtils.generateJWT(studentId, SystemConstant.TYPE_STUDENT);

        HashMap<String, String> data = new HashMap<>();
        data.put("token", token);
        return ResponseResult.ok(data);
    }

    @Override
    public StudentInfoVo getStuById(String stuId) {
        Student student = getOne(new QueryWrapper<Student>().eq("student_id", stuId));
        StudentInfoVo studentInfoVo = BeanCopyUtil.copyBean(student, StudentInfoVo.class);
        return studentInfoVo;
    }

    @Override
    public void updateStuInfo(Student studentInfo) {
        studentInfo.setStudentPassword(SecureUtil.md5(studentInfo.getStudentPassword()));

        update(studentInfo, new QueryWrapper<Student>().eq("student_id", studentInfo.getStudentId()));
    }

    @Override
    public void signOffById(String id) {
        remove(new QueryWrapper<Student>().eq("student_id", id));
    }

}

